<template>
    <div class="content flex-col">
        <div class="tenant-header flex-row">
            <div class="tenant-header-left">
                租户管理
            </div>
            <div class="tenant-header-right">
                <a-button type="primary" @click="handleAdd">
                    <a-icon type="plus" />
                    添加租户
                </a-button>
            </div>
        </div>
        <div class="tenant-content tenant-table">
            <el-table
                    :data="tenants"
                    row-class-name="category-table-tr"
                    height="100%"
                    style="width: 100%">
                <el-table-column
                        prop="tenantId"
                        label="租户ID">
                </el-table-column>
                <el-table-column
                        prop="tenantName"
                        label="租户名称">
                </el-table-column>
                <el-table-column
                        prop="tenantAdminName"
                        label="管理员账号">
                </el-table-column>
                <el-table-column>
                    <template slot="header" slot-scope="scope">
                        <el-input
                                v-model="searchInput"
                                size="mini"
                                style="width: 200px;"
                                placeholder="输入关键字搜索"/>
                    </template>
                    <template slot-scope="scope">
                        <el-button icon="el-icon-edit"
                                   v-if="scope.row.tenantId && scope.row.tenantId !== '000000'"
                                   @click="handleUpdate(scope.row)"
                                   type="text">修改</el-button>
                        <el-button @click="handleConfigTenant(scope.row)"
                                   v-if="scope.row.tenantId && scope.row.tenantId !== '000000'"
                                   type="text">修改租户信息</el-button>
                        <el-button icon="el-icon-delete"
                                   v-if="scope.row.tenantId && scope.row.tenantId !== '000000'"
                                   @click="handleDelete(scope.row)"
                                   type="text" style="color: red">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="tenant_floor">
            <el-pagination
                @size-change="pageSizeChange"
                @current-change="pageChange"
                :current-page="page.currentPage"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="submitState.state === 'add' ? '一 添加租户 一' : '一 修改信息 一'"
                   key="tenant-add"
                   center
                   :visible.sync="dialogVisible"
                   @close="dialogVisible = false"
        >
            <el-form :model="form" :rules="formRules" ref="ruleForm" >
                <el-form-item label="租户名称："
                              :label-width="formLabelWidth"
                              prop="tenantName">
                    <el-input v-model="form.tenantName"></el-input>
                </el-form-item>
                <el-form-item label="账 号："
                              v-if="submitState.state === 'add'"
                              :label-width="formLabelWidth"
                              prop="tenantUserName">
                    <el-input v-model="form.tenantUserName"></el-input>
                </el-form-item>
                <el-form-item label="密 码："
                              v-if="submitState.state === 'add'"
                              :label-width="formLabelWidth"
                              prop="tenantPassword">
                    <el-input v-model="form.tenantPassword"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="formSubmit('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="一 修改租户账户信息 一"
                   key="tenant-modify"
                   width="500px"
                   center
                   :visible.sync="dialogUpdateVisible"
        >
            <el-form :model="form_TenantInfo">
                <el-form-item label="版 本：" :label-width="formLabelWidth">
                    <el-select v-model="form_TenantInfo.version" placeholder="请选择">
                        <el-option value="企业版">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间：" :label-width="formLabelWidth">
                    <el-date-picker
                            v-model="form_TenantInfo.beginDate"
                            type="date"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间：" :label-width="formLabelWidth">
                    <el-date-picker
                            v-model="form_TenantInfo.endDate"
                            type="date"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="是否试用：" :label-width="formLabelWidth">
                    <el-switch
                            v-model="form_TenantInfo.isTrial">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogUpdateVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="formUpdateSubmit()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getTenantList, addTenant, deleteTenant, editTenant, getUserById, getTenantInfo, updateTenantInfo} from '@/api/authority'

    export default {
        name: "tenant",
        data() {
            return {
                dialogVisible: false,
                submitState: {
                    state:'add',
                    node: {}
                },
                page: {
                    pageSize: 10,
                    currentPage: 1
                },
                form: {
                    tenantName: '',
                    tenantUserName: '',
                    tenantPassword: '',
                },
                formRules: {
                    tenantName: [
                        { required: true, message: '请输入租户名称', trigger: 'blur' },
                    ],
                    tenantUserName: [
                        { required: true, message: '请输入租户账号', trigger: 'blur' },
                        { validator: this.checkData, trigger: 'blur'},
                        { min: 2, message: '长度大于 2 个字符', trigger: 'blur' }
                    ],
                    tenantPassword: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                        { validator: this.checkData, trigger: 'blur'}
                    ],
                },

                dialogUpdateVisible: false,
                form_TenantInfo: {
                    version: "企业版",
                    beginDate: "",
                    endDate: "",
                    isTrial: true
                },

                formLabelWidth: '120px',
                searchInput: '',
                tableData: []
            }
        },
        computed:{
            tenants() {
                let {searchInput, tableData, page: {currentPage, pageSize}} = this;
                let filterData = tableData.filter(data => !searchInput || data.tenantAdminName.toLowerCase().includes(searchInput.toLowerCase()) || data.tenantId.toLowerCase().includes(searchInput.toLowerCase()) || data.tenantName.toLowerCase().includes(searchInput.toLowerCase()))
                return filterData.slice((currentPage-1)*pageSize,currentPage*pageSize)
            },
            total() {
                return this.tableData.length;
            }
        },
        methods:{
            getList() {
                getTenantList().then((res) => {
                    if(res.data && res.data.success){
                        this.tableData = [];
                        for (let i = 0; i < res.data.data.length; i++) {
                            let user = res.data.data[i];
                            this.tableData.push({
                                tenantId: user.tenantId,
                                tenantName: user.tenantName,
                                tenantAdminName: user.admin.username
                            })
                        }
                    }
                })
            },
            pageSizeChange(value) {
                this.page.currentPage = 1
                this.page.pageSize = value;
            },
            pageChange(value) {
                this.page.currentPage = value;
            },
            formSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.dialogVisible = false;
                        if (this.submitState.state === "add") {
                            getUserById({
                                username: this.form.tenantUserName
                            }).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.error("账号已存在，请重新添加！");
                                    this.dialogFormVisible = true;
                                }else {
                                    let data = {
                                        "tenantName": this.form.tenantName,
                                        "username": this.form.tenantUserName,
                                        "password": this.form.tenantPassword
                                    }
                                    addTenant(data).then((res) => {
                                        if(res.data && res.data.success){
                                            this.$message.success("添加成功！")
                                            this.getList();
                                        }else {
                                            this.$message.error("添加失败！")
                                        }
                                    })
                                }

                            })
                        }
                        else if (this.submitState.state === "update") {
                            let data = {
                                "tenantId": this.submitState.node.tenantId,
                                "tenantName": this.form.tenantName
                            }
                            // console.log(data)
                            editTenant(data).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.success("修改成功！")
                                    this.getList();
                                } else {
                                    this.$message.error("修改失败！")
                                }
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            handleAdd() {
                this.form = {
                    tenantName: '',
                    tenantUserName: '',
                    tenantPassword: '',
                }

                this.submitState.state = "add";
                this.dialogVisible = true;
            },
            handleUpdate(row) {
                this.submitState = {
                    state: "update",
                    node: row
                };
                this.form.tenantName = row.tenantName;
                this.dialogVisible = true;
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteTenant({"tenantId": row.tenantId}).then((res) => {
                        if (res.data && res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getList();
                        } else {
                            this.$message.error("删除失败！")
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handleConfigTenant(row){
                getTenantInfo({
                    tenantId: row.tenantId
                }).then((res) => {
                    if(res.data && res.data.success){
                        this.dialogUpdateVisible = true;
                        this.form_TenantInfo = res.data.data.account;
                        this.submitState.node = row;
                    }
                })
            },
            formUpdateSubmit(){
                updateTenantInfo({
                    "account": this.form_TenantInfo,
                    "tenantId": this.submitState.node.tenantId
                }).then((res) => {
                    if(res.data && res.data.success){
                        this.dialogUpdateVisible = false;
                        this.$message.success("修改成功！");
                    }else {
                        this.$message.error("修改失败！");
                    }
                })
            }
        },
        created() {
            this.getList();
        }
    }
</script>